import type {
  CreateCrudOptionsProps,
  CreateCrudOptionsRet,
  CrudExpose,
} from '@fast-crud/fast-crud';

import type { FormRulesExt } from '#/api';
import type { ComFileModel } from '#/api/devOperation/system/model/comFileModel';
import type { ActionEnum } from '#/enums/commonEnum';

import { ref } from 'vue';

import { useAccess } from '@vben/access';
import { $t } from '@vben/locales';

import { AutoComplete } from 'ant-design-vue';

import { asyncFindUrlById, downloadFile } from '#/api';
import { ComFileApi } from '#/api/devOperation/system/comFile';
import Avatar from '#/components/view/components/avatar.vue';
import { PermCode } from '#/enums/perm';
import { useMessage } from '#/hooks/web/useMessage';
import {
  backendDict,
  createdTimeColumn,
  deleteButton,
  indexColumn,
} from '#/plugins/fast-crud/common';
import { downloadByResponse, formatFileSize } from '#/utils/file/download';

const { hasPermission } = useAccess();
const permCode = PermCode.devOperation.system.defFile;

export function createCrudOptions(
  props: CreateCrudOptionsProps<ComFileModel.ComFileResultVO, any>,
): CreateCrudOptionsRet<ComFileModel.ComFileResultVO> {
  const selectedRowKeys = ref<string[]>([]);
  const { createMessage, createConfirm } = useMessage();

  async function onView(row: ComFileModel.ComFileResultVO) {
    const response = await downloadFile([row.id as string]);
    downloadByResponse(response);
    createMessage.success($t('common.tips.downloadSuccess'));
  }
  return {
    crudOptions: {
      request: {
        pageRequest: ComFileApi.pageRequest,
        addRequest: ComFileApi.addRequest,
        delRequest: ComFileApi.delRequest,
        infoRequest: ComFileApi.infoRequest,
      },
      actionbar: {
        buttons: {
          add: { show: hasPermission(permCode.debugUpload), text: '调试上传' },
          ...deleteButton({
            crudExpose: props.crudExpose,
            selectedRowKeys,
            role: permCode.delete,
            removeFn: ComFileApi.remove,
          }),
          batchDownload: {
            show: hasPermission(permCode.download),
            text: $t('common.title.download'),
            click() {
              if (selectedRowKeys.value?.length > 0) {
                createConfirm({
                  iconType: 'warning',
                  content: `确定要批量下载${selectedRowKeys.value.length}条记录吗`,
                  onOk: async () => {
                    const response = await downloadFile(selectedRowKeys.value);
                    downloadByResponse(response);
                    createMessage.success($t('common.tips.downloadSuccess'));
                  },
                });
              } else {
                createMessage.warning('请先勾选您要删除的数据');
              }
            },
          },
        },
      },
      addForm: { wrapper: { title: '调试上传' } },
      form: {
        col: { span: 24 },
        wrapper: {
          buttons: { ok: { show: false } },
        },
      },
      table: {
        striped: true,
        rowKey: 'id',
        rowSelection: {
          type: 'checkbox',
          selectedRowKeys,
          onChange: (changed: string[]) => {
            selectedRowKeys.value = changed;
          },
        },
      },
      rowHandle: {
        width: '150px',
        buttons: {
          edit: { show: false },
          view: { show: false },
          copy: { show: false },
          remove: { show: hasPermission(permCode.delete) },
          down: {
            show: hasPermission(permCode.download),
            text: '下载',
            size: 'small',
            type: 'link',
            order: 0,
            async click({ row }) {
              const response = await downloadFile([row.id as string]);
              downloadByResponse(response);
              createMessage.success($t('common.tips.downloadSuccess'));
            },
          },
        },
      },
      columns: {
        ...indexColumn(props.crudExpose),
        id: {
          title: '预览',
          // type: 'avatar-uploader',
          // type: 'image-uploader',
          type: 'file-uploader',
          form: {
            component: {
              valueType: 'key',
              buildUrl: async (res: string) => {
                const file = await asyncFindUrlById(res);
                return file.data;
              },
              uploader: {
                param: () => {
                  const formData = props.crudExpose.getFormData();

                  return {
                    ...formData,
                  };
                },
              },
            },
          },
          column: {
            component: {
              buildUrl: async (key: string) => {
                const file = await asyncFindUrlById(key);
                return file.data;
              },
              render: (value) => {
                return value.row.fileType === 'IMAGE' ? (
                  <>
                    <Avatar
                      height={'50px'}
                      value={value.value}
                      width={'50px'}
                    />
                  </>
                ) : (
                  <>
                    <a
                      href={'javascript:;'}
                      onClick={onView.bind(null, value.row)}
                    >
                      {value.row.originalFileName}
                    </a>
                  </>
                );
              },
            },
          },
        },

        originalFileName: {
          title: $t('devOperation.system.comFile.originalFileName'),
          type: 'text',
          search: { show: true },
          form: { show: false },
        },
        bucket: {
          title: $t('devOperation.system.comFile.bucket'),
          type: 'text',
          search: { show: true },
          form: {
            rules: [{ required: true }],
            value: 'dev',
            component: {
              name: AutoComplete,
              options: [
                {
                  label: '私有资源',
                  value: 'dev',
                  key: 'dev',
                },
                {
                  label: '公共资源',
                  value: 'public',
                  key: 'public',
                },
              ],
            },
          },
        },
        bizType: {
          title: $t('devOperation.system.comFile.bizType'),
          type: 'text',
          form: { rules: [{ required: true }], value: 'BASE__FILE' },
        },
        fileType: {
          title: $t('devOperation.system.comFile.fileType'),
          type: 'dict-radio',
          dict: backendDict({ type: 'FileType', isEnum: true }),
          column: { component: { color: 'auto' } },
          form: { show: false },
        },
        storageType: {
          title: $t('devOperation.system.comFile.storageType'),
          type: 'dict-select',
          dict: backendDict({ type: 'FileStorageType', isEnum: true }),
          column: { component: { color: 'auto' } },
          search: { show: true },
          form: { rules: [{ required: true }], value: 'LOCAL' },
        },
        contentType: {
          title: 'ContentType',
          type: 'text',
          search: { show: true },
          form: { show: false },
        },
        size: {
          title: $t('devOperation.system.comFile.size'),
          type: 'text',
          form: { show: false },
          column: {
            formatter({ value }) {
              return formatFileSize(value);
            },
          },
        },

        ...createdTimeColumn({}),
      },
    },
  };
}

export const frontRules = (
  _crudExpose: CrudExpose,
  _mode: ActionEnum,
): FormRulesExt => {
  return {};
};
